import React, { PureComponent } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Card, Tree, Row, Col, Table, Button, message, Modal } from 'antd';
import { getAccess } from '@/utils/accessFunctions';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import AddOrgMenuInfo from "./addOrgMenuInfo"
import UpdateOrgMenuInfo from "./updateOrgMenuInfo"
import styles from "./index.less"
const confirm = Modal.confirm;
const { TreeNode } = Tree;
const tree_icon = {
    all: require("@/assets/org_all.png"),
    company: require("@/assets/org_company.png"),
    team: require("@/assets/org_team.gif"),
}
@connect(({ system, loading, menuTree }) => ({
    system,
    loading: loading.models.system,
    menuTree: menuTree.menuData,
}))
class CardList extends PureComponent {
    constructor(props){
        super(props)

        this.state = {
            treeData: [],
            modalVisible:false,
            modalUpdateVisible:false,
            SelectID:[],
            SelectObj:{},
            dataRef:{},
            inTeamLists: {}, //已经分配的车辆
            outTeamLists: {},//未分配的车辆
            inTeamPage: {
                page: 1,
                pageSize: 15,
                teamId: 0
            },//车队中的已经分配的车辆分页信息	
            outTeamPage: {
                page: 1,
                pageSize: 15,
                teamId: 0
            },//车队中的未分配的车辆分页信息	
            selectedRowKeysIn:[],
            selectedRowKeysOut:[],
            level:null,
            orginize:""
        }

    }
    columnsL = [{
        title: '序号',
        render: (text, record, index) => `${index + 1}`,
    }, {
        title: '车牌',
        dataIndex: 'plateNo',
    },{
        title:"所属组织",
        render:()=>{
            return this.state.orginize
        }
    }];
    columns = [{
        title: '序号',
        render: (text, record, index) => `${index + 1}`,
    }, {
        title: '车牌',
        dataIndex: 'plateNo',
    }];
    componentDidMount() {
        const {dispatch} = this.props

        dispatch({
            type:"system/fetchOrganize",
            payload:{
                menuId:0
            },
            callback:(res)=>{
                if(res.code !== "000000"){message.warning(res.msg);return}
                this.setState({
                    treeData: res.orgMenuList
                })
            }
        })

    }
    onLoadData = treeNode => new Promise((resolve) => {
        const { dispatch } = this.props

        if (treeNode.props.children) {
            resolve();
            return;
        }

        dispatch({
            type: "system/fetchOrganize",
            payload: {
                menuId: treeNode.props.dataRef.id
            },
            callback: (res) => {
                treeNode.props.dataRef.children = res.orgMenuList
                this.setState({
                    treeData: [...this.state.treeData],
                });
                resolve();
            }
        })
    })
    renderTreeNodes = data => data.map((item) => {
        if (item.children) {
            return (
                <TreeNode title={item.name} key={item.id} dataRef={item} icon={<img src={item.orgType==1 ? tree_icon.company : tree_icon.team} />}>
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            );
        }
        if (Object.keys(item).length == 0) return
        return <TreeNode title={item.name} key={item.id} dataRef={item} isLeaf={item.leaf ? false : true} icon={<img src={item.orgType==1 ? tree_icon.company:tree_icon.team} />}/>;
    })
    /**
     * 新增组织信息--弹窗
     * handleAdd(确定回调),handleModalVisible
     */
    chanceModel = () => {
        const {SelectID} = this.state
        if (SelectID === undefined || SelectID.length == 0) {
            message.warning("请选择对应的节点！")
            return
        }
        this.handleModalVisible(true)
    }
    handleAdd = fields => {
        const { dispatch} = this.props
        let {dataRef} = this.state
        dispatch({
            type: "system/fetchAddOrganize",
            payload: fields,
            callback: (res) => {
                if (res.code !== "000000") { message.warning(res.msg); return }
                if (dataRef.props.eventKey == "0"){
                    var data = dataRef.props.dataRef.concat(res.orgMenuEntity)
                    this.setState({
                        treeData: data//[...this.state.treeData],
                    });
                }else{
                    const children = dataRef.props.dataRef.children
                    if (children){
                        children.push(res.orgMenuEntity)
                        this.setState({
                            treeData: [...this.state.treeData],
                        });
                    }else{
                        dataRef.props.dataRef.leaf = 1
                        this.setState({
                            treeData: [...this.state.treeData],
                        });
                    }
                }
                this.handleModalVisible()
            }
        })
    };
    handleModalVisible = flag => {
        this.setState({
            modalVisible: !!flag,
        });
    };
    /**
     * 新增组织信息--获取目标ID
     * onSelectClick
     * fetchQueryVehicleInOrg -- 查询已经分配的车辆和没有分配的车辆列表信息
     */
    onSelectClick = (selectedKeys, e)=>{
        console.log(selectedKeys)
        const {dispatch} = this.props
        const { inTeamPage,outTeamPage} = this.state
        if (!selectedKeys.length){
            this.setState({
                SelectID: selectedKeys,
            });
            return
        } 
        const data = {
            inTeam:{
                ...inTeamPage,
                teamId: parseInt(selectedKeys[0])
            },
            outTeam:{
                ...outTeamPage
            }
        }
        this.setState({
            SelectID:selectedKeys,
            SelectObj:e.node.props.dataRef,
            dataRef: e.node,
            inTeamPage: data.inTeam,
            outTeamPage:data.outTeam,
            level: e.node.props.dataRef ?e.node.props.dataRef.level:null,
            orginize:e.node.props.dataRef.name
        })
        dispatch({
            type: "system/fetchQueryVehicleInOrg",
            payload: data,
            callback: (res) => {
                if(res.code !== "000000"){message.warning(res.msg);return}
                this.setState({
                    inTeamLists: res.inTeamVehicleList,
                    outTeamLists: res.outTeamVehicleList
                })
            }
        })
    }
    /**
     * 车辆分页
     * handleInTeamChange
     * handleOutTeamChange
     */
    handleInTeamChange = (pagination, filtersArg, sorter) => {
        const { dispatch } = this.props;
        const { inTeamPage, outTeamPage } = this.state;
        
        const inParams = {
            ...inTeamPage,
            page: pagination.current,
            pageSize: pagination.pageSize,
        };
        this.setState({
            inTeamPage: inParams,
        });

        const data = {
            inTeam: inParams,
            outTeam: outTeamPage
        }
        dispatch({
            type: "system/fetchQueryVehicleInOrg",
            payload: data,
            callback: (res) => {
                if (res.code !== "000000") { message.warning(res.msg); return }
                this.setState({
                    inTeamLists: res.inTeamVehicleList,
                    outTeamLists: res.outTeamVehicleList
                })
            }
        })
    };
    handleOutTeamChange = (pagination, filtersArg, sorter) => {
        const { dispatch } = this.props;
        const { inTeamPage, outTeamPage } = this.state;

        const outParams = {
            ...inTeamPage,
            page: pagination.current,
            pageSize: pagination.pageSize,
        };
        this.setState({
            outTeamPage: outParams,
        });

        const data = {
            inTeam: inTeamPage,
            outTeam: outParams
        }
        dispatch({
            type: "system/fetchQueryVehicleInOrg",
            payload: data,
            callback: (res) => {
                if (res.code !== "000000") { message.warning(res.msg); return }
                this.setState({
                    inTeamLists: res.inTeamVehicleList,
                    outTeamLists: res.outTeamVehicleList
                })
            }
        })
    };
    /**
     * 车辆 操作
     * 移至车队--移除车队
     * flag ?'移至车队':'移除车队'
     * move2team
     */
    move2team=(flag)=>{
        const {dispatch} = this.props;
        const { SelectID, selectedRowKeysIn, selectedRowKeysOut} = this.state;
        let data = null;
        if(flag){
            data = {
                vehicleIdList: selectedRowKeysOut,
                teamId: parseInt(SelectID[0])
            } 
        }else{
            data = {
                vehicleIdList: selectedRowKeysIn,
                teamId: 0
            } 
        }    
        dispatch({
            type:"system/fetchVehicleAllocate",
            payload:data,
            callback:(res)=>{
                if(res.code !== "000000"){message.warning(res.msg);return;}
                console.log(res)
                dispatch({
                    type: "system/fetchQueryVehicleInOrg",
                    payload: {
                        inTeam:{
                            ...this.state.inTeamPage
                        },
                        outTeam:{
                            ...this.state.outTeamPage
                        }
                    },
                    callback: (res) => {
                        if (res.code !== "000000") { message.warning(res.msg); return }
                        this.setState({
                            inTeamLists: res.inTeamVehicleList,
                            outTeamLists: res.outTeamVehicleList, 
                            selectedRowKeysIn: [],
                            selectedRowKeysOut: [],
                        })
                    }
                })
            }
        })           
    }
    /**
     * 修改组织信息
     * chanceUpdateModel--获取修改目标ID
     */
    chanceUpdateModel = () => {
        const { SelectID } = this.state
        console.log(SelectID, SelectID === undefined || SelectID.length == 0 || SelectID[0] == "0")
        if (SelectID === undefined || SelectID.length == 0 || SelectID[0] == "0") {
            message.warning("请选择对应的节点！")
            return
        }
        this.handleUpdateModalVisible(true)
    }
    handleUpdate = fields => {
        const { dispatch } = this.props
        let { dataRef } = this.state
        console.log(fields)
        if (fields.pid == 0 && fields.orgType == 2){
            message.warning("此处不可以创建车队！！");
            return 
        }
        if (fields.pid !== 0 && fields.orgType == 1){
            message.warning("此处不可以创建公司！！");
            return 
        }
        dispatch({
            type: "system/fetchUpdateOrgMenuInfo",
            payload: fields,
            callback: (res) => {
                if (res.code !== "000000") { message.warning(res.msg); return }

                dataRef.props.dataRef.name = res.orgMenuEntity.name
                dataRef.props.dataRef.leaf = res.orgMenuEntity.leaf
                dataRef.props.dataRef.orgType = res.orgMenuEntity.orgType

                this.setState({
                    treeData: [...this.state.treeData],
                });
                this.handleUpdateModalVisible()
            }
        })
    }
    handleUpdateModalVisible = flag => {
        this.setState({
            modalUpdateVisible: !!flag,
        });
    };
    // 删除组织
    handleRemove = ()=>{
        const { dispatch } = this.props
        const { SelectID, dataRef } = this.state
        const _this = this
        if (SelectID === undefined || SelectID.length == 0) {
            message.warning("请选择对应的节点！")
            return
        }
        confirm({
            title: '数据删除后将无法还原！是否删除？',
            onOk() {
                return new Promise((resolve, reject) => {
                    dispatch({
                        type:"system/fetchDeleteOrgMenuInfo",
                        payload:{
                            orgId: parseInt(SelectID)
                        },
                        callback:(res)=>{
                            if (res.code !== "000000") { message.warning(res.msg); return }
                            const data = dataRef.props.dataRef
                            for (let key in data) {
                                delete data[key]
                            }
                            _this.setState({
                                treeData: [..._this.state.treeData],
                            });
                            message.success("删除成功！！")
                            resolve()
                        }
                    })

                }).catch(() => console.log('Oops errors!'));
            },
            onCancel() { },
        });
    }
    render() {
        const { inTeamLists, outTeamLists, treeData, modalVisible, modalUpdateVisible, SelectObj, selectedRowKeysIn, selectedRowKeysOut, SelectID, level, orginize} = this.state
        const ID = SelectID.length == 0 || SelectID[0] == "0"
        const rowSelectionIn = {
            selectedRowKeys: selectedRowKeysIn,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRowKeysIn: selectedRowKeys
                })
            }
        };
        const rowSelectionOut = {
            selectedRowKeys: selectedRowKeysOut,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRowKeysOut: selectedRowKeys
                })
            }
        };
        // 新建
        const addOrgFn = {
            handleAdd: this.handleAdd,
            handleModalVisible: this.handleModalVisible,
        };
        // 修改
        const updateOrgFn = {
            handleUpdate: this.handleUpdate,
            handleUpdateModalVisible: this.handleUpdateModalVisible,
        };
        const moveHeight={
            height: document.getElementById("move_height")
        }
        return (
            <PageHeaderWrapper Breadcrumb>
                <Card bordered={false}>
                    <Row id="move_height">
                        <Col lg={{ span: 24 }} xl={{ span: 7 }}>
                            <Tree showIcon={true} loadData={this.onLoadData} onSelect={this.onSelectClick} defaultExpandedKeys={['0']}>
                                <TreeNode title="全部" key="0" icon={<img src={tree_icon.all} />} dataRef={treeData}>
                                    {this.renderTreeNodes(treeData)}
                                </TreeNode>
                            </Tree>
                            <div className={styles.butGroup}>
                                <Button type="primary" size="small" onClick={this.chanceModel} disabled={level >= 3}>新增组织</Button>
                                <Button size="small" onClick={this.chanceUpdateModel}>修改组织</Button>
                                <Button type="danger" size="small" onClick={this.handleRemove}>删除组织</Button>
                                {/* <Button type="dashed" size="small">移动组织</Button> */}
                            </div>
                        </Col>
                        <Col lg={{ span: 10 }} xl={{ span: 7 }}>
                            <Table 
                                className={styles.antTable_org}
                                rowSelection={rowSelectionIn} 
                                columns={this.columnsL} 
                                dataSource={inTeamLists.list} 
                                pagination={inTeamLists.pagination}
                                onChange={this.handleInTeamChange}
                                rowKey={record => record.id}
                                size="small"/>
                        </Col>
                        <Col lg={{ span: 4 }} xl={{ span: 3 }}>
                            <div style={{textAlign:"center"}}>
                                <div style={{marginBottom:10}}>
                                    <Button type="primary" size="small" icon="left-circle" onClick={() => this.move2team(true)} disabled={ID || selectedRowKeysOut.length == 0}>移至车队</Button>
                                </div>
                                <div>
                                    <Button type="primary" size="small" icon="right-circle" onClick={() => this.move2team(false)} disabled={ID || selectedRowKeysIn.length == 0}>移除车队</Button>
                                </div>
                            </div>
                        </Col>
                        <Col lg={{ span: 10 }} xl={{ span: 7}}>
                            <Table 
                                rowSelection={rowSelectionOut} 
                                columns={this.columns}
                                dataSource={outTeamLists.list} 
                                pagination={outTeamLists.pagination}
                                onChange={this.handleOutTeamChange}
                                rowKey={record => record.id}
                                size="small" />
                        </Col>
                    </Row>
                </Card>
                {/* 新增 */}
                <AddOrgMenuInfo modalVisible={modalVisible} {...addOrgFn} SelectObj={SelectObj} orginize={orginize} />
                {/* 修改 */}
                {SelectObj && Object.keys(SelectObj).length && modalUpdateVisible ?
                    <UpdateOrgMenuInfo modalVisible={modalUpdateVisible} {...updateOrgFn} SelectObj={SelectObj} />
                :null }
            </PageHeaderWrapper>
        );
    }
}

export default CardList;
